package com.whj.account.captcha;

import com.google.code.kaptcha.Producer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountCaptchaServiceImpl implements AccountCaptchaService{
    private List<String> predefindedTexts;
    private Map<String,String> captchaMap = new HashMap<>();
    private Producer    producer;

    public void setProducer(Producer producer) {
        this.producer = producer;
    }

    @Override
    public String generateCaptchaKey() throws AccountCaptchaException {

        String key = RandomGenerator.getRandomString();
        String value = getCaptchaText();
        this.captchaMap.put(key, value);

        return key;
    }

    @Override
    public byte[] generateCaptchaImage(String key) throws AccountCaptchaException {
        String value = this.captchaMap.get(key);
        if(value == null){
            throw new AccountCaptchaException(String.format("调用generateCaptchaImage失败，找不到key('%s')对应的值", value));
        }

        BufferedImage image = this.producer.createImage(value);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "JPG", stream);
        }catch (IOException exp) {
            throw new AccountCaptchaException("");
        }

        return stream.toByteArray();
    }

    @Override
    public void validateCaptcha(String captchaKey, String captchaValue)  throws AccountCaptchaException{
        String text = this.captchaMap.get(captchaKey);

        if(text == null){
            throw new AccountCaptchaException(String.format("调用validateCaptcha失败，找不到key('%s')", captchaKey));
        }

        this.captchaMap.remove(captchaKey);
        if(!text.equals(captchaValue.trim())) {
            throw new AccountCaptchaException("验证码错误");
        }
    }

    @Override
    public List<String> getPredefinedTexts() {
        return this.predefindedTexts;
    }

    @Override
    public void setPredefinedTexts(List<String> texts) {
        this.predefindedTexts = texts;
    }

    private int nextPredefinedTextIndex = -1;
    private String getCaptchaText(){
        if(this.predefindedTexts != null && this.predefindedTexts.size() > 0){
            this.nextPredefinedTextIndex = (this.nextPredefinedTextIndex + 1) % this.predefindedTexts.size();
            return this.predefindedTexts.get(this.nextPredefinedTextIndex);
        } else {
            return this.producer.createText();
        }
    }
}
